import { objectAny } from "../../options/base";
import { showModal } from "../../utils/utils";
import { db_riderTurnOrder, db_startGrabOrder, db_submitSelfOrder } from "../db/order-manage";
import { cameraSelectImage } from "./native";
import { uniCloudUploadFile } from "./uniCloud";


export type dragBtnStyleRule = {
    customClass:string;
    btnText:string;
    showTurnOrderBtn:boolean;
    action:(serverData:objectAny)=>Promise<any>
}
export type orderTypeRule = 0|1|2|4
export type tabListModuleRule=Array<{
    name:string;
    icon:string;
    list:Array<any>;
    value:orderTypeRule;
    loadStatus:`fulfilled`|`pending`;
    fastBtnStyle?:{
        customClass:string;
        btnText:string;
    };
    dragBtnStyle:dragBtnStyleRule,
    current_loca_ms?:number
}>
export function statusToTabList(
    tabList:tabListModuleRule,
    status:0|1|2|3
){
    // 前者为服务器上的订单状态  后者为对于的tabbar状态
    const toggleStatus={
        0:0,
        1:1,
        2:2,
        3:2,
    }
    const tabStatus=toggleStatus[status]
    if(tabStatus==null){
        return {}
    }
    const tabItem = tabList.filter((it)=>it.value===tabStatus)[0]
    return tabItem
}
// 移除table列表数据中 已经滑动的数据
export function removeTableListIndexData(
    currentTable:tabListModuleRule[0],
    dbId:string
){
    const tableIndex=currentTable.list.findIndex(it=>it._id === dbId)
    if(tableIndex!==-1){
        currentTable.list.splice(tableIndex,1)
    }
}

export function buildTabListModule(
    afterActionList:Array<(index:number,dbId:string)=>Promise<any>>
):tabListModuleRule{
    return [{
        name:`新订单`,
        icon:`paperclip`,
        list:[],
        value:0,
        loadStatus:`fulfilled`,
        dragBtnStyle:{
            customClass:`grab_order_class`,
            btnText:`立即抢单`,
            showTurnOrderBtn:false,
            action:async (serverData)=>{
                const dbId = serverData._id
                // tab1开始抢单 获取当前订单
                const refresh = await db_startGrabOrder(dbId,serverData.order_id);
                if(refresh){
                    const index = 0
                    return afterActionList[index](index,dbId);
                }
            }
        }
    },{
        name:`待取货`,
        icon:`flag`,
        list:[],
        value:1,
        loadStatus:`fulfilled`,
        fastBtnStyle:{
            customClass:`have_picked_up_class`,
            btnText:`扫码取货`
        },
        dragBtnStyle:{
            customClass:`have_picked_up_class`,
            btnText:`我已取货`,
            showTurnOrderBtn:true,
            action:async (serverData)=>{
                const dbId = serverData._id
                // tab2我已取货
                // 将订单状态修改为 派送中
                const refresh = await db_submitSelfOrder(dbId,serverData.order_id,3);
                if(refresh){
                    const index = 1
                    return afterActionList[index](index,dbId);
                }
            }
        }
    },{
        name:`配送中`,
        icon:`paperplane`,
        list:[],
        value:2,
        loadStatus:`fulfilled`,
        fastBtnStyle:{
            customClass:`complete_order_class`,
            btnText:`扫码送达`
        },
        dragBtnStyle:{
            customClass:`complete_order_class`,
            btnText:`我已送达`,
            showTurnOrderBtn:true,
            action:async (serverData)=>{
                const result= await showModal({
                    title:`操作提示`,
                    content:`提交前请先拍摄物品存放位置`
                })
                let filePath:string|null = null
                let fileServerID:string|null = null
                if(result){
                    const {code,data}= await cameraSelectImage();
                    if(code === 0){
                        const [receiptImgPath] = (data?.list) as Array<string>;
                        filePath = receiptImgPath
                    }
                }
                const dbId = serverData._id
                uni.showLoading({
                    title: `正在提交`,
                    mask:true
                });
                try {
                    if(filePath){
                        const {success:fileSuccess,fileID}=await uniCloudUploadFile(filePath);
                        // 图片上传完成
                        if(fileSuccess){
                            fileServerID = fileID
                            console.log(fileServerID)
                            console.log(`回执图片上传完成，现在开始提交该订单的成功状态`)
                        }
                    }
                    // tab3 完成配送 订单已完成
                    // 将订单状态修改为 派送中
                    const refresh = await db_submitSelfOrder(dbId,serverData.order_id,4,{
                        fileID:fileServerID
                    },false);
                    uni.hideLoading();
                    if(refresh){
                        const index = 2
                        return afterActionList[index](index,dbId)
                    }
                } catch (error) {
                    console.error(error)
                    uni.hideLoading();
                }
            }
        }
    }]
}

function scanCodeCommon():Promise<{
    status:boolean;
    success?:objectAny;
    error?:objectAny;
}>{
    return new Promise(resolve=>{
        uni.scanCode({
            // 只允许通过相机扫码
            onlyFromCamera: true,
            success: res=> {
                return resolve({
                    status:true,
                    success:res
                })
            },
            fail:(err:any)=>{
                console.error(err)
                if(err.errMsg===`scanCode:fail method 'uni.scanCode' not supported`){
                    showModal({
                        title:`异常提示`,
                        content:`当前设备不支持扫码，请联系客服`,
                        showCancel:false
                    })
                }
                return resolve({
                    status:false,
                    error:err
                })
            }
        })
    })
}


// 扫码转单操作
export async function turnOrderScanCode(
    dbId:string,
    orderId:string
):Promise<boolean>{
    if(dbId==null){
        showModal({
            title:`异常提示`,
            content:`暂无法执行转单，请稍后再试`,
            showCancel:false
        })
        return false
    }
    const {status,success} = await scanCodeCommon();
    if(status){
        const { result,scanType} =  success as objectAny;
        if(scanType === `QR_CODE` && result !== ``){
            try {
                const decodstr = decodeURIComponent(result);
                const {uid} = JSON.parse(decodstr)
                if(uid){
                    console.log(`当前解析出来后的参数uid: ${uid}`)
                    await db_riderTurnOrder(dbId,orderId,uid);
                    return true
                }
            } catch (error) {
                console.error(error)
            }
        }
        showModal({
            title:`异常提示`,
            content:`该二维码异常，请联系客服`,
            showCancel:false
        })
    }
    return false

}

// 通过扫描订单小票上的二维码 完成以下操作
// 1. 我已取货
// 2. 我已送达
export function scanCodeChangeOrder(
    tabItem:tabListModuleRule[0]
):Promise<boolean>{
    return new Promise(async resolve=>{
        if(tabItem.list.length===0){
            showModal({
                title:`操作提示`,
                content:`当前暂无任何需要处理的订单`,
                showCancel:false
            })
            return resolve(false)
        }
        const {status,success} = await scanCodeCommon()
        if(status){
            const { result,scanType} =  success as objectAny;
            if(scanType === `QR_CODE` && result !== ``){
                try {
                    const decodstr = decodeURIComponent(result);
                    const {id,orderId} = JSON.parse(decodstr)
                    if(id && orderId){
                        await tabItem.dragBtnStyle.action({
                            _id:id,
                            order_id:orderId
                        })
                        return  resolve(true)
                    }
                } catch (error) {
                    console.error(error)
                }
            }
            showModal({
                title:`异常提示`,
                content:`该二维码异常，请联系客服`,
                showCancel:false
            })
            return resolve(false)
        }
        return resolve(false)

    })
}